﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GzipManagerPro.IO.Helpers
{
    public static class Compressor
    {
        public static byte[] ToGzip(this byte[] data)
        {
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            GZipStream compressor = new GZipStream(memoryStream, CompressionMode.Compress);
            compressor.Write(data, 0, data.Length);
            compressor.Close();

            byte[] result = memoryStream.ToArray();
            memoryStream.Close();

            return result;
        }

        public static byte[] FromGzip(this byte[] data)
        {
            
            int length = BitConverter.ToInt32(data, data.Length - 4);

            byte[] buffer = new byte[length];

            MemoryStream stream = new MemoryStream(data);
            GZipStream decompressor = new GZipStream(stream, CompressionMode.Decompress);
            decompressor.Read(buffer, 0, buffer.Length);

            decompressor.Close();
            stream.Close();

            return buffer;
        }

        public static int GetOriginalLength(this byte[] buffer)
        {
            return BitConverter.ToInt32(buffer, buffer.Length - 4);
        }
    }
}
